package com.wsn.smarthouse;

import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
//import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.Message;
//import android.util.Log;
//import android.widget.Toast;
import android.util.Log;
//import com.wsn.util.Log;

//TODO: Check the structure can be use
public class NetService extends Service{
	
	private DatagramSocket ds1 = null;
	private RecThread rt;
	private AliveThread alivethread;
	public final static String logtag = "netservice";
	public static HashMap<String, String> nodesensorlist = 
			new HashMap<String, String>();
	
	
	@Override
	public IBinder onBind(Intent intent){
		
		return null;
	}
	
	public static class InnerReceiver extends BroadcastReceiver {  
		  
        @Override  
        public void onReceive(Context context, Intent intent) { 
        	if (!intent.getStringExtra("dingyue").equals("dingyue")){
        		Iterator<Entry<String, String>> iter = 
        				nodesensorlist.entrySet().iterator(); 
        		while (iter.hasNext()) { 
        			Map.Entry<String,String> entry = 
        					(Entry<String, String>) iter.next(); 
        			String key = (String)entry.getKey(); 
        			String val = (String)entry.getValue(); 
        			String regEx="LED";
        			Pattern p=Pattern.compile(regEx);
        			Matcher m=p.matcher(key);
        			boolean result=m.find();
        			Log.v(logtag,"compare result"+result);
        			Log.v(logtag,(String)key);
        			Log.v(logtag,(String)val);
        		} 
        	}
        	else{
        		Message msg = new Message();
        		msg.obj="watch"+nodesensorlist.get("红外幕屏");
        		AliveThread.alivehandler.sendMessage(msg);
        	}
        	
        }
	}
	
	
	
	@Override
	public void onCreate(){
		try{	
			ds1 = new DatagramSocket();
		}catch(SocketException i)
		{
			
		}
		alivethread= new AliveThread(ds1);
		rt = new RecThread(ds1,nodesensorlist);
		alivethread.start();
		rt.start();
	}
	
	@Override
	public void onDestroy(){
		rt.interrupt();
		alivethread.interrupt();
		ds1=null;
		super.onDestroy();
	}
	
}
